package com.kalua.list.harvester.resultprocessing;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kalua.list.domainmodel.retailer.CrawlBatchInfo;

public class FileBasedResultProcessorFactory implements ResultProcessorFactory {

	private static final Logger logger = 
			LoggerFactory.getLogger(FileBasedResultProcessorFactory.class);
	
	protected static String DATA_FILE_EXTENSION = ".data";
	
	private File targetDirectory;
			
	public FileBasedResultProcessorFactory(final String outputPath) {
		super();
		
		String path;
		if (StringUtils.isEmpty(outputPath)) {			
			path = FileUtils.getTempDirectoryPath();
			logger.info("Defaulting output path to: {}.", path);
		} else path = outputPath;
		
		File candidateDirectory = new File(path);
		if (!candidateDirectory.isDirectory()) {
			logger.info("Directory '{}' doesn't exist, will create.", path);
			candidateDirectory.mkdirs();
		}
		
		this.targetDirectory = candidateDirectory;				
	}

	@Override
	public ResultProcessor createResultProcessor(CrawlBatchInfo batchInfo) {
		FileBasedResultProcessor result;
		String outputFileName = 
				batchInfo.getId() + DATA_FILE_EXTENSION;
		
		File outputFile = new File(this.targetDirectory,outputFileName);
		result = new FileBasedResultProcessor(outputFile);
		return result;
	}
}
